// pages/category/index.js
import {request} from '../../request/index.js'
import regeneratorRuntime from '../../lib/runtime/runtime.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    leftCategory: [],
    rightCategory: [],
    rightSecondCategory: [],
    currentIndex: 0,
    index: 0,
    scrollTop: -1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const cates = wx.getStorageSync("cates");
    if(!cates) {
      // 本地存储里不存在，就重新发送请求获取数据
     this.getLeftCategory()
    } else {
      // 本地的数据超过十秒就重新发送数据
      if(Date.now() - cates.time > 1000*10) {
        this.getLeftCategory()
      } else {
        // 可以使用旧的数据
        this.cate = cates.data
        
      let leftCategory = this.cate.map(v => {
        return v.cat_name
      })
      let rightCategory = this.cate[0].children
      this.setData({
        leftCategory,
        rightCategory
      })
      }
    }
  },
  changeIndex: function (e) {
    console.log(e.currentTarget.dataset.index)
    let index = e.currentTarget.dataset.index
    let rightCategory = this.cate[index].children
      this.setData({
        currentIndex: index,
        rightCategory,
        scrollTop: 0
      })
    
  },
  // getLeftCategory: function () {
  //   request({
  //     url: '/categories'
  //   }).then(data => {
  //     this.cate = data.data.message
  //     // 把接口的数据存到本地存储中
  //     wx.setStorageSync('cates', {time: Date.now(), data: this.cate})

  //     let leftCategory = this.cate.map(v => {
  //       return v.cat_name
  //     })
  //     let rightCategory = this.cate[0].children
  //     this.setData({
  //       leftCategory,
  //       rightCategory,
  //       scrollTop: 0
  //     })
  //   })
  // }



  async getLeftCategory () {
    var data = await request({url: '/categories'})
      this.cate = data.data.message
      // 把接口的数据存到本地存储中
      wx.setStorageSync('cates', {time: Date.now(), data: this.cate})

      let leftCategory = this.cate.map(v => {
        return v.cat_name
      })
      let rightCategory = this.cate[0].children
      this.setData({
        leftCategory,
        rightCategory,
        scrollTop: 0
      })
    
  }

})